<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import {type FormItemRows, QForm} from "@meetjs/element-plus-kit";
import axios from "axios";

const opts1 = [{label: "男", value: "男"}, {label: "女", value: "女"}];
import { Plus } from '@element-plus/icons-vue'
import {ElMessage, type UploadProps, type UploadUserFile} from 'element-plus'

const fileList = ref<UploadUserFile[]>([
])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const userInfo = reactive({
  username: '',
  password: '',
  name: "",
  tel: '',
  mail: '',
  identificationCard: '',
  bornDate: '',
  sexs: '',
  headimgurl: ''
})
const headers = {
  token: localStorage.getItem("doctor-auth-token")
}
const getUserInfo = () => {
  axios.post("/api/auth/userinfo", {}, {headers})
      .then(res => {
        console.log(res);
        const msg = res.data.message
        // Object.assign(userInfo,msg)
        userInfo.username = msg.username
        userInfo.name = msg.name
        userInfo.tel = msg.tel
        userInfo.mail = msg.mail
        userInfo.identificationCard = msg.identificationCard
        userInfo.bornDate = msg.bornDate
        userInfo.sexs = msg.sexs
        userInfo.headimgurl = msg.headimgurl
        userInfo.password = ''
        if(res.data.message.headimgurl){
          fileList.value = [
            {
              name: 'headimgurl',
              url: res.data.message.headimgurl,
            }
          ]
        }
      })
}
onMounted(() => {
  getUserInfo()
})

const formRef = ref<any>(null);
const formOptions = ref<FormItemRows[]>([
  {type: "input", label: "用户名", prop: "username"},
  {type: "input", label: "姓名", prop: "name"},
  {type: "input", label: "密码(设置即重置)", prop: "password"},
  {type: "input", label: "电话", prop: "tel"},
  {type: "input", label: "邮箱", prop: "mail"},
  {type: "input", label: "身份证", prop: "identificationCard"},
  {type: "select-v2", label: "性别", prop: "sexs", options: opts1},
  {type: "date-picker", label: "出生日期", prop: "bornDate",},
  {type: "slot", label: "头像", prop: "customslot",},
]);
const uploadImage = async (option: any) => {
  const formData = new FormData();
  formData.append('file', option.file);

  try {
    const res = await axios.post('/api/upload/img', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        token: localStorage.getItem("doctor-auth-token") || ''
      }
    });

    // ✅ 设置头像地址（用于提交）
    userInfo.headimgurl = res.data.message;
    console.log(res)
    // ✅ 更新 fileList 中的 url 显示
    fileList.value = [];
    fileList.value=[
      {
        name: option.file.name,
        url: res.data.message,
      }
    ]

    // 通知上传成功（必须调用，否则 element upload 状态不更新）
    option.onSuccess(res.data, option.file);
  } catch (error) {
    option.onError(error);
  }
};

const onSubmit = () => {
  console.log(userInfo);
  axios.post("/api/auth/update/user",userInfo,{headers})
      .then(res=>{
        console.log(res);
        if(res.data.success){
          ElMessage({
            type:"success",
            message:"更新成功"
          })
        }else{
          ElMessage({
            type:"error",
            message:res.data.message
          })
        }
        setTimeout(()=>{
          getUserInfo()
        },3000)
      })
};

</script>

<template>
  <div>
    <QForm ref="userInfo" :buttons="[ { label: '保存信息', type: 'submit' }]"
           :formOptions="formOptions" :model="userInfo"
           label-width="125px" @submit="onSubmit" title="个人信息" style="width: 40vw;max-width: 700px">
      <template #customslot>
        <el-upload
            v-model:file-list="fileList"
            :http-request="uploadImage"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            limit="1"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>


        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </template>
    </QForm>
  </div>
</template>

<style lang="scss" scoped>

</style>
